<template>
	<el-dialog title="角色设置" v-model="isShowDialog" width="450px" :close-on-click-modal="false"
		:close-on-press-escape="false">
		<p> 当前账号 {{ruleForm.AccountName}}</p>
		<div ref="checkListref">
			<div v-for="roles in Roles" class="mb20 mt20 checkboxList">
				<label v-if="roles.UsersID"> <input type="checkbox" :value="roles.ID" checked /> {{roles.Name}} </label>
				<label v-else> <input type="checkbox" :value="roles.ID" /> {{roles.Name}} </label>
			</div>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="onCancel" size="default" >关 闭</el-button>
				<el-button type="primary" @click="onSubmit" size="default"> 提交 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts">
	import {
		reactive,
		toRefs,
		onMounted,
		ref,
	} from 'vue';
	import {
		getUsersRolesAPI,
		saveRolesAPI
	} from '/@/api/users/index';
	import {
		ElForm,
		ElMessage
	} from 'element-plus';
	export default {
		name: '',
		setup() {
			const checkListref = ref();
			const state = reactive({
				isShowDialog: false,
				ruleForm: {
					ID: '0'
				},
				Roles: []
			});
			// 打开弹窗
			const openDialog = (model: Object, callback: Function) => {
				state.ruleForm = model;
				state.isShowDialog = true;
				state.callback = callback;
				init();
			};
			// 关闭弹窗
			const closeDialog = () => {
				state.Roles = [];
				state.isShowDialog = false;

			};
			// 取消
			const onCancel = () => {
				closeDialog();
			};

			// 页面加载时
			onMounted(() => {

			});
			const init = () => {

				let ID = state.ruleForm.ID;
				getUsersRolesAPI({
					ID
				}).then(async (response) => {
					//console.log(response);
					if (response['code'] === 0) {
						state.Roles = response.result;

					}
				});

			}
			const onSubmit = () => {

				let values = [];
				let list = checkListref.value.getElementsByTagName('input');

				for (let i = 0; i < list.length; i++) {

					if (list[i].checked) {
						values.push(list[i].value);
					}
				}
				let ID = state.ruleForm.ID;
				let Roles = values.join(",");
				//console.log(Roles);
				saveRolesAPI({
					ID,
					Roles
				}).then(async (response) => {

					if (response['code'] === 0) {

						if (state.callback) {

							state.callback();
						}
						ElMessage.success(`${response.message}`);
						closeDialog();
					}


				});
			}

			return {
				openDialog,
				closeDialog,
				onCancel,
				...toRefs(state),
				onSubmit,
				checkListref
			};
		},
	};
</script>

<style scoped lang="scss">
	.checkboxList {

		label {

			input {
				position: relative;
				top: 1.8px;
			}
		}
	}
</style>
